package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.vo.OrderReportVO;
import com.sky.vo.SalesTop10ReportVO;
import com.sky.vo.TurnoverReportVO;
import com.sky.vo.UserReportVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *数据统计接口实现类
 */
@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;


    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverData(LocalDate begin, LocalDate end) {
        //先构造dateList，存放begin到end的日期
        List<LocalDate> dateList = new ArrayList<>();

        dateList.add(begin);
        while (!begin.equals(end)){
            //日期加1天
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        //构造turnoverList，存放日期对应的营业额数据
        List<Double> turnoverList = new ArrayList<>();

        for (LocalDate date : dateList) {
            //根据日期查询对应的营业额数据
            //sql:select sum(amount) from orders where order_time between beginTime and endTime and status = 5

            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("beginTime",beginTime);
            map.put("endTime",endTime);
            map.put("status",5);
            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;//如果为空，则赋值为0
            turnoverList.add(turnover);
        }


        return TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserData(LocalDate begin, LocalDate end) {
        //先构造dateList，存放begin到end的日期
        List<LocalDate> dateList = new ArrayList<>();

        dateList.add(begin);
        while (!begin.equals(end)){
            //日期加1天
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        //构造newUserList，存放日期对应新增的用户数据
        List<Integer> newUserList = new ArrayList<>();

        for (LocalDate date : dateList) {
            //根据日期查询对应的新增用户数据
            //sql:select count(id) from user where create_time > beginTime create_time < endTime

            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap();
            map.put("beginTime",beginTime);
            map.put("endTime",endTime);

            Integer totalUser = userMapper.countByMap(map);
            totalUser = totalUser == null ? 0 : totalUser;
            newUserList.add(totalUser);
        }

        //构造totalUserList，存放日期对应总用户数据
        List<Integer> totalUserList = new ArrayList<>();
        for (LocalDate date : dateList) {
            //根据日期查询对应的总用户数据
            //sql:select count(id) from user where create_time < endTime

            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap();
            map.put("endTime",endTime);
            Integer totalUser = userMapper.countByMap(map);
            totalUser = totalUser == null ? 0 : totalUser;
            totalUserList.add(totalUser);
        }

        return UserReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();
    }

    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrderData(LocalDate begin, LocalDate end) {
        //1.先构造dateList，存放begin到end的日期
        List<LocalDate> dateList = new ArrayList<>();

        dateList.add(begin);
        while (!begin.equals(end)){
            //日期加1天
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //2.构造orderCountList，存放日期对应订单总数
        List<Integer> orderCountList = new ArrayList<>();
        for (LocalDate date : dateList) {
            //根据日期查询对应的订单总数
            //sql:select count(id) from orders where order_time > beginTime order_time < endTime

            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap();
            map.put("beginTime",beginTime);
            map.put("endTime",endTime);

            Integer totalOrderCount = orderMapper.countByMap(map);
            totalOrderCount = totalOrderCount == null ? 0 : totalOrderCount;
            orderCountList.add(totalOrderCount);
        }

        //3.构造validOrderCountList，存放日期对应有效订单总数
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate date : dateList) {
            //根据日期查询对应的有效订单总数
            //sql:select count(id) from orders where order_time > beginTime order_time < endTime and status = 5

            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Map map= new HashMap();
            map.put("beginTime",beginTime);
            map.put("endTime",endTime);
            map.put("status",5);//已完成
            Integer validOrderCount = orderMapper.countByMap(map);
            validOrderCount = validOrderCount == null ? 0 : validOrderCount;
            validOrderCountList.add(validOrderCount);
        }

        //4.查询订单完成率 = 有效订单总数/订单总数，从beginTime到endTime
        LocalDateTime beginTime = LocalDateTime.of(dateList.get(0), LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(dateList.get(dateList.size()-1), LocalTime.MAX);
        //4.1 查询订单总数 sql:select count(id) from orders where order_time > beginTime order_time < endTime
        Map map = new HashMap();
        map.put("beginTime",beginTime);
        map.put("endTime",endTime);
        Integer totalOrderCount = orderMapper.countByMap(map);
        //4.2 查询有效订单总数 sql:select count(id) from orders where order_time > beginTime order_time < endTime and status = 5
        map.put("status",5);
        Integer validOrderCount = orderMapper.countByMap(map);
        //4.3 计算订单完成率
        Double orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;



        return OrderReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .orderCompletionRate(orderCompletionRate)
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .build();
    }

    /**
     * 销量排名Top10
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        //sql:select od.name,sum(od.number) as number from orders o,order_detail od where o.id = od.order_id and o.status = 5 and o.order_time > beginTime and o.order_time < endTime
        // group by od.name
        // order by number desc
        // limit 0,10
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime, endTime);

            //将List<GoodsSalesDTO>转换为List<String>
        List<String> names = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numbers = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        return SalesTop10ReportVO
                .builder()
                .nameList(StringUtils.join(names, ","))
                .numberList(StringUtils.join(numbers, ","))
                .build();
    }
}
